package tuvienna.jade.participant;

import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import tuvienna.jade.CentralRandom;
import tuvienna.jade.Constants;

/**
 * Handling the registration of a participant to a table
 */
public class RequestTableSizeBehaviour extends Behaviour {

	private static final long serialVersionUID = 1809253456702899176L;
	private boolean done = false;
	private int step = 0;
	protected ParticipantAgent participant;
	private TableInformation table;
	private MessageTemplate mt;
	
	public RequestTableSizeBehaviour(ParticipantAgent participant, TableInformation table) {
		super();
		this.participant = participant;
		this.table = table;
	}

	public void action() {
		switch(step) {
		case 0:
			ACLMessage sizeRequest = new ACLMessage(ACLMessage.REQUEST);
			sizeRequest.addReceiver(table.getAID());
			sizeRequest.setConversationId(getConversationID());
			String msgId = participant.getLocalName()+"/"+table.getAID().getLocalName()
					+"/"+CentralRandom.nextInt(10000);
			sizeRequest.setReplyWith(msgId);
			participant.send(sizeRequest);
			step = 1;
			
			mt = MessageTemplate.and(MessageTemplate.MatchConversationId(getConversationID()),
									 MessageTemplate.MatchInReplyTo(msgId));
			break;
		case 1:
			ACLMessage reply = participant.receive(mt);
			if (reply != null) {
				String content = reply.getContent();
				String[] entries = content.split(Constants.FIELD_DELIMITER);
				int size = new Integer(entries[1]);
				table.setSize(size);
				done = true;
			} else { 
				block();
			}
			break;
		}
		
	}

	public boolean done() {
		return done;
	}
	
	protected String getConversationID() {
		return Constants.TABLE_SIZE_REQUEST;
	}
		
}